var parent_comment = 0;

function reply_comment(comment){
	parent_comment = comment;
	$("#reply_comment_block").hide(200);
	setTimeout(function(){$("#reply_comment_block").appendTo("#comment_"+comment+" .reply_this_comment:eq(0)").show(200)},190);
	setTimeout(function(){$("#reply_comment_name").length ? $("#reply_comment_name").focus() : $("#reply_comment_text").focus()},200);
}

function add_comment(params,length,foo){
	$.ajax({
		url: "/ajax/reply",
		type: "POST",
		data: params,
		success: function(data){
			if (data != "name" && data != "text")
			{
				var response = $.parseJSON(data);
				var userPic = response['user_id'] != 0 ? "<a href='/user/"+response['login']+"'>"+response['img']+"</a>" : response['img'];
				var userName = response['user_id'] != 0 ? "<a class='user_link' href='/user/"+response['login']+"'>"+response['name']+"</a>" : "<span class='guest'>"+response['name']+"</span>";
				var div = "\
					<div class='comment' id='comment_"+response['comment_id']+"'>\
						<a name='comment_"+response['comment_id']+"' class='anchor'><table><tr>\
							<td class='comment_user'>"+userPic+"</td>\
							<td>\
								<div class='comment_body'>\
									<div class='comment_head'><a class='comment_link' href='/news/"+$("#news_id").val()+"#comment_"+response['comment_id']+"'>#</a> "+
									userName+"<span class='comment_time'>"+response['time']+"</span></div>\
									<div class='comment_text'>"+response['text']+"</div>\
									<div class='reply_this_comment'>\
										<a class='reply_this_comment_button' href='javascript:reply_comment("+response['comment_id']+")'>ответить</a>\
									</div>\
								</div>\
							</td></tr></table>\
						</a>\
					<div class='reply_comment'"+(length > 9 ? "style='margin-left:0'" : "")+"></div></div>";
				foo(div);
			}
		}
	})
}

$(document).ready(function(){
	
	/*************** main page ***************/
	$(".tabs").click(function(){
		$("#mediatabs .active").removeClass("active");
		$(this).addClass("active");
		$(".content").fadeOut(0);
		var img = $(".tabs").index(this)+1;
		$(".content:nth-child("+img+")").fadeIn(0);
		$(".media_preview").fadeOut(0);
		$(".media_preview:nth-child("+img+")").fadeIn(0);
	})
	
	var news_timer = setInterval(function(){
		if ($("#mediatabs .active").hasClass("video"))
		{
			clearInterval(news_timer);
			return;
		}
		if ($("#mediatabs .active").attr("id") == "mediatabright")
			$("#mediatableft").click();
		else
			$("#mediatabs .active").next().click();
	},10000);
	
	/*************** news ***************/
	$("#news a").attr("target","_blank");
	$(".hinted").hover(function(){
		var div = $(this).find(".hint");
		var margin = (div.width() - $(this).width())/2;
		div.css({"margin-left":"-"+margin+"px"}).fadeIn(200);
	},function(){
		var div = $(this).find(".hint");
		div.fadeOut(200);
	})
	
	/*************** comment ***************/
	$(".rBorder").keydown(function(e){
		if (e.keyCode != 9)
			$(this).removeClass("red");
	})
	
	$("#reply_text").keydown(function(e){
		if (e.keyCode == 10 || e.keyCode == 13 && (e.ctrlKey || e.metaKey && browser.mac))
			$("#reply_this").click();
	});
	
	$("#reply_comment_text").keydown(function(e){
		if (e.keyCode == 10 || e.keyCode == 13 && (e.ctrlKey || e.metaKey && browser.mac))
			$("#reply_comment_this").click();
		if (e.keyCode == 27)
			$("#reply_comment_cancel").click();
	});
	$("#reply_comment_name").keydown(function(e){
		if (e.keyCode == 10 || e.keyCode == 13 && (e.ctrlKey || e.metaKey && browser.mac))
			$("#reply_comment_this").click();
		if (e.keyCode == 27)
			$("#reply_comment_cancel").click();
	});
	
	$("#reply_comment_cancel").click(function(){
		$("#reply_comment_block").hide(200);
		$("#reply_comment_name").val("");
		$("#reply_comment_text").val("");
		parent_comment = 0;
	})
	
	$("#reply_comment_this").click(function(){
		if ($("#reply_comment_name").val() == "")
			$("#reply_comment_name").focus();
		else if ($("#reply_comment_text").val() == "")
			$("#reply_comment_text").focus();
		else
		{
			var params = "reply="+encodeURIComponent($("#reply_comment_text").val())+"&parent_id="+parent_comment+"&news_id="+$("#news_id").val()+
				($("#reply_comment_name").val() ? "&name="+encodeURIComponent($("#reply_comment_name").val()) : "");
			add_comment(params,$("#reply_comment_this").parents(".comment").length,function(div){
				$("#reply_comment_this").parents(".comment:eq(0)").find(".reply_comment:eq(0)").append(div);
				$("#reply_comment_name").val("");
				$("#reply_comment_text").val("");
				$("#reply_comment_cancel").click();
			});
		}
	})
	
	$("#reply_this").click(function(){
		if ($("#reply_name").val() == "")
			$("#reply_name").focus();
		else if ($("#reply_text").val() == "")
			$("#reply_text").focus();
		else
		{
			var params = "reply="+encodeURIComponent($("#reply_text").val())+"&parent_id=0"+"&news_id="+$("#news_id").val()+($("#reply_name").val() ? "&name="+encodeURIComponent($("#reply_name").val()) : "");
			var container = $("#commentblock .comment:last");
			add_comment(params,0,function(div){
				$("#reply").before(div);
				$("#reply_name").val("");
				$("#reply_text").val("");
			});
		}
	})
	
	/*************** images ***************/
	if ($("a.images").length != 0)
	{
		$("a.images").fancybox({
			'transitionIn'	:	'fade',
			'transitionOut'	:	'fade',
			'speedIn'		:	600, 
			'speedOut'		:	100, 
			'cyclic'		:	true
		})
	}
	
	/*************** voting ***************/
	var input = "";
	$(".info").hover(function(){
		$(this).find(".checkbox:not(.choosen)").attr("src","/files/img/check_hover.png");
	},function(){
		$(this).find(".checkbox:not(.choosen)").attr("src","/files/img/check.png");
	})
	$(".info").click(function(){
		$(".choosen").attr("src","/files/img/check.png").removeClass("choosen");
		$(this).find(".checkbox").attr("src","/files/img/check_on.png").addClass("choosen");
		input = $(this).attr("id");
	})
	$(".alink").click(function(e){
		e.stopPropagation();
	})
	$("#vote").click(function(e){
		$.ajax({
			url: "/ajax/vote",
			type: "POST",
			data: "choice="+input,
			success: function(data){
				switch(data){
					case "vote": alert("Вы уже голосовали!"); break;
					case "candidate": alert("Необходимо выбрать кандидата!"); break;
					default: window.location.reload();
				}
			}
		})
	})
	
	
	/*************** registration ***************/
	function addDays(){
		var dayInMonths = [31,28,31,30,31,30,31,31,30,31,30,31];
		var day = $("#birthday").val();
		var year = $("#birthyear").val();
		var month = $("#birthmonth").val();
		
		if (year%4 == 0)
			dayInMonths[1]++;
		
		$("#birthday option").remove();
		for (var i=1; i <= dayInMonths[month-1]; i++)
			$("#birthday").append("<option value='"+i+"'>"+i+"</option>");
		
		if (day > dayInMonths[month-1])
			$("#birthday option:last").attr("selected","selected");
		else
			$("#birthday option:eq("+(day-1)+")").attr("selected","selected");
	}
	
	$("#birthmonth").change(addDays);
	$("#birthyear").change(addDays);
	
	function makeRed(o){
		o.css("border","1px solid red");
	}
	$(".enter").keydown(function(e){
		if ($(this).attr("id") == "login")
			$("#exists_error").fadeOut(0);
		else if ($(this).attr("id") == "email")
			$("#email_error").fadeOut(0);
	});
	
	function checkLogin(){
		var exists = false;
		$.ajax({
			url: "/ajax/checklogin",
			data: "type=login&login="+$("#login").val(),
			type: "post",
			async: false,
			success: function(data){
				if (data)
					exists = true;
			}
		})
		
		return exists;
	}
	
	function checkEmail(){
		var exists = false;
		$.ajax({
			url: "/ajax/checklogin",
			data: "type=email&email="+$("#email").val(),
			type: "post",
			async: false,
			success: function(data){
				if (data)
					exists = true;
			}
		})
		
		return exists;
	}
	
	var lTimer = 0;
	$("#login").keyup(function(){
		clearTimeout(lTimer);
		lTimer = setTimeout(function(){
			if (checkLogin())
			{
				makeRed($("#login").focus());
				$("#exists_error").fadeIn(0);
			}
		},1000);
	});
	
	var eTimer = 0;
	$("#email").keyup(function(){
		clearTimeout(eTimer);
		eTimer = setTimeout(function(){
			if (checkEmail())
			{
				makeRed($("#email").focus());
				$("#email_error").fadeIn(0);
			}
		},1000);
	});
	
	$("#male").click(function(){
		$("#sex_error").fadeOut(0);
	})
	$("#female").click(function(){
		$("#sex_error").fadeOut(0);
	})
	
	$("#regForm").submit(function(){
		if (!/^[a-zA-zа-яА-Я]+\w*$/.test($("#login").val()))
			makeRed($("#login").focus());
		else if (checkLogin())
			{
				makeRed($("#login").focus());
				$("#exists_error").fadeIn(0);
			}
		else if ($("#password").val() == "")
			makeRed($("#password").focus());
		else if ($("#re_password").val() == "")
			makeRed($("#re_password").focus());
		/* else if (!/^[а-яА-Я-]+$/.test($("#sname").val()))
			makeRed($("#sname").focus()); */
		else if (!/^[а-яА-Я-]+$/.test($("#name").val()))
			makeRed($("#name").focus());
		/* else if (!/^[а-яА-Я-]+$/.test($("#tname").val()))
			makeRed($("#tname").focus()); */
		else if (!/^[\w\-\.]+@[\w\-\.]+\.[a-zA-Z]{2,}$/.test($("#email").val()))
			makeRed($("#email").focus());
		else if (checkEmail())
			{
				makeRed($("#email").focus());
				$("#email_error").fadeIn(0);
			}
		else if ($("#male").attr("checked") != "checked" && $("#female").attr("checked") != "checked")
			{
				$("#sex_error").fadeIn(0);
			}
		else
			return true;
		return false;
	})
	
	/*************** polls ***************/
	$("#pollSend").click(function(){
		if ($(".pollAnswer:checked").length == 1)
		{
			$.ajax({
				url: "/ajax/polls/vote",
				type: "post",
				data: "answer="+$(".pollAnswer:checked").val(),
				success: function(data){
					$("#leftpollitems").html("").hide();
					var colors = ["#e0642e","#2e97e0","#b02ee0","#e02e75","#bce02e","#e0d62e"];
					var answers = $.parseJSON(data);
					for (key in answers){
						if (key < answers.length-1) {
							var span = "<span class='bolder'>"+answers[key]['text']+"</span><span> ("+answers[key]['percent']+"%)</span>";
							var div = "<div class='percentage' style='background-color:"+colors[key]+";width:"+answers[key]['percent']+"%;'>"+span+"</div>";
							$("#leftpollitems").append(div);
						}
					}
					$("#leftpollitems").append("Всего проголосовало: <span class='bolder'>"+answers[answers.length-1]['all_users']+"</span>").fadeIn(200);
					$("#leftpollsubmit").remove();
				}
			})
		}
	})
	
	/*************** cabinet ***************/
	//***** profile
	if ($(".inf").length){
		setTimeout(function(){$(".inf").hide(200)},2000)
	}
	
	//***** messages
	$("#check_all_messages").change(function(){
		console.log("")
		if ($(this).attr("checked")) {
			$(".message_check").attr("checked","checked");
			$("#msgActs").fadeIn(0);
		} else {
			$(".message_check").removeAttr("checked");
			$("#msgActs").fadeOut(0);
		}
	})
	$(".message_check").change(function(){
		if ($(".message_check").length == $(".message_check:checked").length)
			$("#check_all_messages").attr("checked","checked");
		else
			$("#check_all_messages").removeAttr("checked");
		
		if ($(".message_check:checked").length == 0)
			$("#msgActs").fadeOut(0);
		else
			$("#msgActs").fadeIn(0);
	})
	$("#markNewMsg").click(function(){
		MessageAction("new");
	})
	$("#markReadMsg").click(function(){
		MessageAction("read");
	})
	$("#delMsg").click(function(){
		if (confirm("Действительно удалить выбранные сообщения?"))
			MessageAction("delete");
	})
	function MessageAction(action){
		var params = "act="+action+"&userAs="+$("#userAs").val();
		var msgs = $(".message_check:checked");
		if (msgs.length < 1)
			return false;
		msgs.each(function(){
			params += "&msg%5B%5D="+this.value;
		})
		
		$.ajax({
			url: "/cabinet/messages/actions",
			type: "post",
			data: params,
			success: function(){
				window.location.reload();
			}
		})
	}
	
	/*************** rumors ***************/
	var gl_top = 0;
	$(".rumor").each(function(){
		move($(this));
		var k = Math.ceil($(this).find(".rumor_text").html().length/33);
		if (k > 1){
			var width = k*20;
			var margin = (k-1)*10;
			$(this).find(".pplus,.pminus").css("height",width+"px");
			$(this).find(".plus,.minus").css("margin-top",margin+"px");
		}
		$(this).css("top",gl_top+"px");
		gl_top += $(this).height() + 5;
	})
	$("#positive,#negative").css("height",(gl_top+40)+"px");
})

/*************** rumors ***************/
function move(obj){
	var like = obj.find("input.like").val();
	var dislike = obj.find("input.dislike").val();
	var summ = like/1 + dislike/1;
	if (summ != 0){
		var left = dislike/summ*100;
	} else {
		var left = 50;
	}
	var step = (900 - obj.width())/100;
	var position = left * step + 25;
	obj.animate({"margin-left":position});
}

function like(rumor,mean){
	$.ajax({
		url: "/ajax/like",
		data: "rumor="+rumor+"&mean="+mean,
		type: "post",
		success: function(data){
			if (data != "user"){
				var response = $.parseJSON(data);
				$("#rumor_"+rumor).find("input.like").val(response.like);
				$("#rumor_"+rumor).find("input.dislike").val(response.dislike);
				$("#rumor_"+rumor).attr("title","Верят: "+response.like+" | Не верят: "+response.dislike)
				move($("#rumor_"+rumor));
			}
		}
	})
}




